<?php
uses('model');

class itemsModel extends Model {

    function __construct() {
        parent::__construct();
    }

    function itemsList($v) {
        $this->dbconnect();

        $data = array();
        if ($v['sort']) {
            $cols = $this->db->_db->MetaColumnNames($this->table['items']);
            if (!in_array($v['sort'],$cols) && !strpos($v['sort'],',') && $v['sort'] != 'rand()') $v['sort'] = 'a.id';
        } else {
            $v['sort'] = 'a.id';
        }

        $table  = $this->table['items'].' a';
        $field  = '*';

        if (isset($v['ids'])) {
            //多 IN 单 =
            $where = (is_int($v['ids']) ? "id={$v['ids']}" : "id IN({$v['ids']})");

            //单个产品更新浏览数
            if (is_int($v['ids'])) $this->db->Update($this->table['items'], array('views'=>'{[+1]}'), $where);

        } else {

            $_where = $v['where'] ? $v['where'] : '1';
            $where  = $v['search'] ? $this->makelikequery($v['search'], array('name','title','stuff'), $this->db) : $_where;

            //不显示下架商品
            if (!$v['isadmin']) $where = "a.issale=1 AND ({$where})";

            //代销商品限制
            if ($v['loopo_uid'] && !$v['isadmin']) $where = 'a.price3 AND '.$where;

            //按价格搜索
            if ($v['pricefrom']>0)    $where .= " AND price1 >= {$v['pricefrom']}";
            if ($v['priceto']>0)      $where .= " AND price1 <= {$v['priceto']}";

            if ($v['pid']) {
                //查找下属分类
                $cids = $this->db->GetCol($this->table['cats'], 'id', 'pid='.intval($v['pid']));
                if ($cids) $v['pid'] = join(',', $cids);
                $where .= ' AND b.cid IN('. $v['pid'] .') AND a.name <> ""';
                $table = $this->table['itemc'].' b LEFT JOIN '.$this->table['items'].' a ON b.iid=a.id';
                $field = 'DISTINCT iid';
            }
        }

        if ($v['pagesize']) {
            $data['list'] = $this->db->GetPage(array($table, $field, $where." ORDER BY ".$v['sort']." {$v['sortorder']}"), $data['page'], $v['pagesize']);
        } else {
            $data['list'] = $this->db->GetAll($table, $field, $where." ORDER BY ".$v['sort']." {$v['sortorder']}");
        }

        if ($field == 'DISTINCT iid') {
            //预防同一父分类下物品属于两个子分类的时候会重复显示
            if (count($data['list']) > 0) {
                foreach ($data['list'] as $vv) $iids[] = $vv['iid'];
                $data['list'] = $this->db->GetAll($this->table['items'].' a', '*', 'id IN('.join(',', $iids).') ORDER BY '.$v['sort']." {$v['sortorder']}");
            }
        }

        //记录点击
        loads('click');

        //个性属性
        foreach ($data['list'] as $k=>$v) {
            if ($v['cols']) $data['list'][$k]['cols'] = unserialize(trim($v['cols']));
            $data['list'][$k]['price1'] = str_replace('.00', '.-', $v['price1']);

            //PIC
            $data['list'][$k]['pic']['s'] = '/images/items/s/'.$v['model'].'.gif';
            $data['list'][$k]['pic']['m'] = '/images/items/m/'.$v['model'].'.gif';
            $data['list'][$k]['pic']['l'] = '/images/items/l/'.$v['model'].'.gif';

            //Click
            $data['list'][$k]['sig_click'] = clickController::sigGen('',$v['id'],'items:click');
        }

        return $data;
    }

    function itemsEdit($v) {
        $this->dbconnect();

        //传来的分类ID
        if ($v['fields']['pid1']) {
            $pids[1] = $v['fields']['pid1'];
            if ($v['fields']['pid2'] && $v['fields']['pid2'] != $pids[1]) $pids[2] = $v['fields']['pid2'];
            unset($v['fields']['pid1']);
            unset($v['fields']['pid2']);
        }

        /*
        1.update成功
        2.失败
        */
        if ($v['remove']) {
            $data['remove'] = true;
            $this->db->Delete($this->table['items'], "id={$v['id']}");

            //删除购物车
            $this->db->Delete($this->table['shopcar'], "iid={$v['id']}");
            //删除到货通知
            $this->db->Delete($this->table['alert'], "iid={$v['id']}");
            //删除TAGS
            $this->db->Delete($this->table['tagsi'], "iid={$v['id']}");
            //删除分类
            $this->db->Delete($this->table['itemc'], "iid={$v['id']}");
            //删除Wishlist
            $this->db->Delete($this->table['wishlist'], "iid={$v['id']}");

        } else if ($v['copy']) {
            $v['fields'] = $this->db->getRow($this->table['items'], '*', "id={$v['id']}");
            $v['fields']['updated'] = $v['fields']['created'] = time();
            $v['fields']['name'] .= '(Copy)';
            $v['fields']['issale'] = 0;
            unset($v['fields']['id']);
            unset($v['fields']['views']);

            $data['code']['itemsEdit'] = $this->db->Insert($this->table['items'], $v['fields']) ? 1 : 2;
            $data['add'] = true;
            $data['newid'] = $v['id'] = $this->db->insertid();

        } else {
            //Groups cache update
            if ($v['fields']['groupkey']) $this->getGroups($v['fields']['groupkey'], true);

            if ($v['add']) {
                $data['code']['itemsEdit'] = $this->db->Insert($this->table['items'], $v['fields']) ? 1 : 2;

                $data['add'] = true;
                $data['newid'] = $v['id'] = $this->db->insertid();
            } else {
                //物品更新
                $data['code']['itemsEdit'] = $this->db->Update($this->table['items'], $v['fields'], "id={$v['id']}") ? 1 : 2;

                if ($v['fields']['stocknum'] > 0) {
                    //到货通知
                    $f['subject'] = '乐铺到货通知 - '.date('Y-m-d H:i');

                    $rs = $this->db->GetAll($this->table['alert'], "id, email, created", "iid={$v['id']}");
                    if ($rs) foreach($rs as $vv) {
                        $f['mailto']    = $vv['email'];

                        $f['body']  =   "亲爱的用户：\r\n\r\n";
                        $f['body']  .=  "        您在 ". trim(date('y-m-d H:i', $vv['created'])) ." 曾在乐铺上对我们的物品“{$v['fields']['name']}”感兴趣。我们高兴的通知您，目前该物品已经到货 {$v['fields']['stocknum']} 件。\r\n\r\n";
                        $f['body']  .=  "        如果您还有兴趣的话，可以赶快到 http://www.loopo.cn/items/{$v['id']}/ 购买，不要再错过了哦。";

                        $f['created']   = time();

                        //删除已发送提醒
                        if ($this->db->Insert($this->table['mail'], $f)) $this->db->Delete($this->table['alert'], "id={$vv['id']}");
                    }
                }
            }

            //更新分类
            $this->_updateitemclass($pids, $v['id']);
        }
        return $data;
    }

    function catsAdd($v) {
        $this->dbconnect();

        $data['code']['catsAdd'] = $this->db->insert($this->table['cats'], $v) ? 1 : 2;
        $data['id']              = $this->db->insertid();
        $this->db->cacheflush = true;
        $this->db->CacheGetAll($this->table['cats'], '*', "pid={$v['pid']}");
        return $data;
    }

    function catsList($v) {
        $this->dbconnect();

        if ($v['sort']) {
            $cols = $this->db->_db->MetaColumnNames($this->table['cats']);
            if (!in_array($v['sort'],$cols)) $v['sort'] = 'id';
        } else
            $v['sort'] = 'id';

        if ($v['ids']) {
            $where = "id IN({$v['ids']})";
        } else {
            if ($v['pid']) {
                $tmp = $this->db->GetOne($this->table['cats'], 'pid', "id={$v['pid']}");
                if ($tmp!=0) $v['pid'] = $tmp;
                $data['parent'] = $this->db->GetRow($this->table['cats'], '*', "id={$v['pid']}");
            }
            $where = 'pid='.intval($v['pid']);
        }

        $data['list'] = $this->db->GetAll($this->table['cats'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}");
        foreach ($data['list'] as $kk=>$vv) $data['list'][$kk]['list'] = $this->db->CacheGetAll($this->table['cats'], '*', 'pid='.$vv['id']);

        return $data;
    }

    function catsEdit($v) {
        $this->dbconnect();

        $pid = $this->db->GetOne($this->table['cats'], 'pid', "id={$v['id']}");

        /*
        1.update成功
        2.失败
        */
        if ($v['remove']) {
            $data['remove'] = true;
            $this->db->delete($this->table['cats'], "id={$v['id']}");
        } else {
            if ($v['add']) {
                $data['code']['catsEdit'] = $this->db->Insert($this->table['cats'], $v['fields']) ? 1 : 2;
                $data['add'] = true;
            } else
                $data['code']['catsEdit'] = $this->db->Update($this->table['cats'], $v['fields'], "id={$v['id']}") ? 1 : 2;
        }

        $this->db->cacheflush = true;
        $this->db->CacheGetAll($this->table['cats'], '*', "pid=$pid");

        return $data;
    }

    function addToCar($v) {
        $this->dbconnect();

        $where = "iid='{$v['iid']}' AND sessionid='{$v['sessionid']}'";

        /*
        1.成功
        2.参数错误
        4.失败
        8.要购买数大于库存
        */

        $row = $this->db->GetRow($this->table['items'], '*', "id='{$v['iid']}'");

        //购物车中已有物品 ++
        if ($c = $this->db->GetOne($this->table['shopcar'], 'amount', $where)) {
            //直接加1
            //$data['code']['addToCar'] = $this->db->Update($this->table['shopcar'], array('amount'=>'{[+1]}', 'updated'=>time()), $where) ? 1 : 4;

            //要购买数是否大于库存？
            if ($c < $row['stocknum'])
                $data['code']['addToCar'] = $this->db->Update($this->table['shopcar'], array('amount'=>'{[+1]}', 'postfee'=>($c+1)*$row['postfee'], 'updated'=>time()), $where) ? 1 : 4;
            else
                $data['code']['addToCar'] = $this->db->Update($this->table['shopcar'], array('amount'=>$row['stocknum'], 'postfee'=>($row['stocknum']*$row['postfee']), 'updated'=>time()), $where) ? 8 : 4;

        } else {

            /*
            1.加入购物车成功
            2.没有这个产品
            4.插入数据库错误
            */
            if ($row['stocknum'] == 0) {
                $data['code']['addToCar'] = 8;
            } elseif ($row['name'] && $row['price1']) {
                $fields = $v;
                $fields['iname']    = $row['name'];
                $fields['price']    = $row['price1'];
                $fields['amount']   = 1;

                //额外运费
                if ($row['postfee']) $fields['postfee'] = $row['postfee'];

                $fields['updated']  = time();

                $data['code']['addToCar'] = $this->db->insert($this->table['shopcar'], $fields) ? 1 : 4;
            } else {
                $data['code']['addToCar'] = 2;
            }
        }

        //计算总数
        $tmp = $this->db->GetRow($this->table['shopcar'], 'SUM(amount) AS a, SUM(price*amount) as b', "sessionid='{$v['sessionid']}'");
        $data['count'] = $tmp['a'];
        $data['price'] = $tmp['b'];

        return $data;
    }

    function alertMe($v) {
        $this->dbconnect();

        /*
        1.成功
        2.失败
        4.参数不对
        8.没有这个产品
        32.已经登记过了
        */
        if ($data = $this->db->GetRow($this->table['items'], '*', "id={$v['iid']}")) {

            if ($v['email']) {
                $v['created'] = time();
                if ($this->db->Count($this->table['alert'], "iid={$v['iid']} AND email=".$this->db->qstr($v['email'])) > 0 ) {
                    $data['code']['alertMe'] = 32;
                    $this->db->Update($this->table['alert'], $v, "iid={$v['iid']} AND email=".$this->db->qstr($v['email']));
                } else {
                    $data['code']['alertMe'] = $this->db->Insert($this->table['alert'], $v) ? 1 : 2;
                }
            }

        } else {
            $data['code']['alertMe'] = 8;
        }

        return $data;
    }

    function alertList($v) {
        $this->dbconnect();

        if (!$v['sort']) $v['sort'] = 'ct';
        $where = 1;

        if ($v['iid']) {
            $where = "iid = {$v['iid']}";
            $data['detail'] = $this->db->GetAll($this->table['alert'], '*', "iid={$v['iid']} ORDER BY created DESC");
        }

        if ($v['pagesize']) {
            $data['list'] = $this->db->GetPage(array($this->table['alert'].' a LEFT JOIN '.$this->table['items'].' b ON a.iid=b.id', 'a.iid, b.name, COUNT(*) as ct', "$where GROUP BY iid ORDER BY ".$v['sort']." {$v['sortorder']}"), $data['page'], $v['pagesize']);
        } else {
            $data['list'] = $this->db->GetAll($this->table['alert'].' a LEFT JOIN '.$this->table['items'].' b ON a.iid=b.id', 'a.iid, b.name, COUNT(*) as ct', "$where GROUP BY iid ORDER BY ".$v['sort']." {$v['sortorder']}");
        }

        return $data;
    }

    //TAG 列表
    function itemsTagsList($v) {
        $this->dbconnect();

        if ($v['tagname']) {
            $tmp = explode(',', $v['tagname']);
            $tmp = array_unique($tmp);
            $tags = join("','", $tmp);

            $rows    = $this->db->GetAll($this->table['tags'], '*', "name IN('{$tags}')");

            if (count($tmp) == 1) {
                //单个tag的情况
                $sigtag = true;

                $id = $rows[0]['id'];
                $data['row'] = $rows[0];
            } else {
                //多个tag的情况
                foreach ($rows as $row) $id[] = $row['id'];
                $id = join(',', $id);
            }

            if (!$id) return false;

            $table  = $this->table['tagsi'].' a LEFT JOIN '.$this->table['items'].' b ON a.iid=b.id';
            $where  = "a.tid IN($id) AND issale=1";

            if ($v['pagesize']) {
                $data['list'] = $this->db->GetPage(array($table, 'DISTINCT iid', $where), $data['page'], $v['pagesize']);
            } else {
                $data['list'] = $this->db->GetAll($table, 'DISTINCT iid', $where);
            }

            //预防重复显示
            if (count($data['list']) > 0) {
                foreach ($data['list'] as $vv) $iids[] = $vv['iid'];
                $data['list'] = $this->db->GetAll($table, 'DISTINCT a.iid, b.*', 'id IN('.join(',', $iids).') ORDER BY '.$v['sort']." {$v['sortorder']}");
            }

            //记录点击
            include_once CTLS.'click.php';

            //个性属性
            foreach ($data['list'] as $k=>$vv) {
                //非法tag处理
                if (!$vv['name']) {
                    $this->db->Delete($this->table['tagsi'], "iid={$vv['iid']}");
                    unset($data['list'][$k]);
                    $data['page']['total']--;
                }

                //tag 数量
                $recount = $data['page']['total'];

                if ($vv['cols']) $data['list'][$k]['cols']   = unserialize(trim($vv['cols']));

                $data['list'][$k]['price1'] = str_replace('.00', '.-', $vv['price1']);

                //Click
                $data['list'][$k]['sig_click'] = clickController::sigGen('',$vv['id'],'items:click');
            }

            //单个tag请求才处理
            if ($sigtag) {
                //pinyin为空的重新计算
                if (!$data['row']['pinyin']) {
                    uses('pinyin');
                    $py = new pinyin;
                    $fields['pinyin'] = $py->cover($v['tagname'], 'utf-8');
                }
                //tag重新计算数量
                if (isset($recount)) $fields['ct'] = $recount;

                if ($fields) $this->db->Update($this->table['tags'], $fields, "id={$id}");

                //删除0物品标签
                if (count($data['list']) == 0) $this->db->Delete($this->table['tags'], "id={$id}");
            }

        } else {
            $where = $v['where'] ? $v['where'] : 1;
            if ($v['pagesize']) {
                $data['list'] = $this->db->GetPage(array($this->table['tags'], 'name,ct', "$where ORDER BY ".$v['sort']." {$v['sortorder']}"), $data['page'], $v['pagesize']);
            } else {
                $data['list'] = $this->db->GetAll($this->table['tags'], 'name,ct', "$where ORDER BY ".$v['sort']." {$v['sortorder']}");
            }
        }

        return $data;
    }

    //物品TAG
    function itemsTagsGet($v) {
        $this->dbconnect();

        $result = $this->db->GetAll($this->table['tags'].' a LEFT JOIN '.$this->table['tagsi'].' b ON a.id=b.tid', 'id, name, ct', "b.iid={$v['id']}");
        return $result;
    }

    //TAG 更新
    function itemsTagsUpdate($v) {
        $tmp = explode(' ', $v['tags']);

        //tags 格式预处理
        foreach ($tmp as $k=>$tag) {
            $tag = preg_replace('|[\'"\\/]+|', '', $tag);
            if (strlen(trim($tag)) >= 3) $tags[] = trim($tag);
        }
        $tags = array_unique($tags); //重复 tag
        if (!$v['id'] || count($tags) == 0) return false;

        $this->dbconnect();

        $tmp = $this->itemsTagsGet($v);
        if (count($tmp)) {
            foreach ($tmp as $tv) $oldtag[] = $tv['name'];
            $oldtag = join(' ', $oldtag);
            if ($oldtag == $v['tags']) return true;
        }

        //更新TAG数量
        $tmp = $this->db->GetAll($this->table['tagsi'].' a LEFT JOIN '.$this->table['tags'].' b ON a.tid=b.id', 'name, count(*) as ct', "name IN('". join("','", $tags). "') GROUP BY tid");
        foreach ($tmp as $tv) $count[$tv['name']] = $tv['ct'];

        //加载拼音转换类
        uses('pinyin');
        $py = new pinyin;

        foreach ($tags as $t) {
            $pinyin = $py->cover($t, 'utf-8');
            if ($count[$t]) {
                $this->db->Update($this->table['tags'], array('ct'=>$count[$t], 'pinyin'=>$pinyin), 'name='.$this->db->qstr($t));
            } else {
                //if ($this->db->affected_rows() == 0)
                $this->db->Insert($this->table['tags'], array('name'=>$t, 'ct'=>1, 'pinyin'=>$pinyin));
            }
        }

        $dbtags = $this->db->GetCol($this->table['tags'], 'id', "name IN('". join("','", $tags). "')");

        $this->db->Delete($this->table['tagsi'], "iid={$v['id']}");
        foreach ($dbtags as $tid) $this->db->Insert($this->table['tagsi'], array('tid'=>$tid, 'iid'=>$v['id']));

        return true;
    }

    //根据 tagid 获取相关物品资料
    function getItemsByTagId($v) {
        $this->dbconnect();

        foreach ($v['ids'] as $_v) $where[] = "tid=$_v";
        $where = join(' OR ', $where);
        //不显示指定id
        if ($v['deid']) $where = " b.stocknum > 0 AND b.id <> {$v['deid']} AND ($where)";
        $where .= ' AND b.issale=1 ';

        $data['list'] = $this->db->GetAll($this->table['tagsi'].' a LEFT JOIN '.$this->table['items'].' b ON a.iid=b.id', 'DISTINCT(b.id), b.*', $where." ORDER BY RAND() LIMIT {$v['limit']}");

        return $data;
    }

    //购物车：从session更新uid
    function updateShopcarUid($v) {
        $this->dbconnect();
        $this->db->Update($this->table['shopcar'], array('uid'=>$v['uid']), "sessionid='{$v['sessionid']}'");
        $this->db->Update($this->table['shopcar'], array('sessionid'=>$v['sessionid']), "uid='{$v['uid']}'");
        return true;
    }

    //取得指定物品所属的分类 ID
    function getItemsClass($id) {
        $this->dbconnect();
        return $this->db->GetCol($this->table['itemc'], 'cid', "iid={$id} ORDER BY id");
    }

    //取得指定物品所属的分类路径
    function getPath($id) {
        //$this->dbconnect();
    }

    //取得物品分组
    function getGroups($key, $update=false) {
        $this->dbconnect();
        $this->db->cacheflush = $update;
        return $this->db->cacheGetAll($this->table['items'], 'id,groupvalue', 'issale>0 AND groupkey='.$this->db->qstr($key));
    }

    //取得最大 ID
    function getMaxId() {
        $this->dbconnect();
        return $this->db->GetOne($this->table['items'], 'MAX(id)');
    }

    //更新物品分类
    function _updateitemclass($cids, $iid) {
        if (!is_array($cids)) return false;
        $this->dbconnect();

        $this->db->delete($this->table['itemc'], "iid=0");
        $this->db->delete($this->table['itemc'], "iid={$iid}");
        foreach ($cids as $cid) $this->db->insert($this->table['itemc'], array('cid'=>$cid, 'iid'=>$iid));
        return true;
    }
}
?>
